
document.getElementById('start').addEventListener('click', () => {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      func: (n, p) => {
        document.getElementById('zjdm').value = n;
        document.getElementById('pw').value = p;

        window.autoClickerInterval = window.setInterval(() => {
          send();
        }, 500); // 每秒点击2次

        let loading = false;

        send();

        function send() {
          if (loading) {
            return;
          }
          const captcha = document.getElementById('imgVcode');
          captcha.parentElement.click();
          if (!captcha) return;
          window.setTimeout(() => {
            const image = new Image();
            image.src = captcha.src;
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            if (!ctx) {
              return;
            }
            image.onload = () => {
              canvas.width = image.width;
              canvas.height = image.height;
              ctx.drawImage(image, 0, 0)
              const base64 = canvas.toDataURL();
              loading = true;
              fetch('https://ocr.fanchan.org.cn/captcha', { method: 'POST', body: JSON.stringify({ base64 }), headers: { 'content-type': 'application/json' } }).then(res => res.json()).then(res => {
                if (res.data.length !== 4) {
                  loading = false;
                  return;
                }
                document.getElementById('code').value = res.data;
                document.getElementById('getKshBtn').removeAttribute('disabled');
                document.getElementById('getKshBtn').click();

                window.setTimeout(() => {
                  const options = Array.from(document.getElementById('username').children);
                  document.getElementById('username').value = options[options.length - 1].value
                  document.getElementById('logicBtn').click();

                  loading = false;
                }, 100);
              }).catch(e => {
                loading = false;
                console.log(e);
              });
            }
          }, 10);
        }
      },
      args: [username, password]
    });
  });
});

document.getElementById('stop').addEventListener('click', () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    chrome.scripting.executeScript({
      target: { tabId: tabs[0].id },
      function: stopAutoClicker
    });
  });
});

function stopAutoClicker() {
  clearInterval(window.autoClickerInterval);
}